Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Polymorphism in java

Constructor overloading

Constructor overloading in Java allows us to have multiple constructors with different argument lists. This is a form of static polymorphism (compile-time polymorphism) which helps us to initialize an object in different ways. Here are different ways to perform constructor overloading

Example 1 : Constructor overloading example with and without parameters

Changing the Number of Parameters Constructor overloading can be achieved by changing the number of parameters while passing to different constructors. Here’s an example:
Constructor overloading example with and without parameters(default) in java class Product { public Product() { System.out.println("This is a default constructor"); } public Product(int i, String n) { System.out.println(n +", This is a parameterized constructor"); } } class Main { public static void main(String[] args) { Product obj1 = new Product(); Product obj2 = new Product(1,"Hello"); } }

Output

This is a default constructor Hello, This is a parameterized constructor

Example 2 : Constructor overloading example with different datatype

Changing Data Types of the Arguments In many cases, constructors can be considered overloaded if they have the same name but have different parameter types. Here’s an example:
Constructor overloading example with different datatype in java class Product { public Product(int a, int b) { System.out.println("This is a constructor with integer parameters"); } public Product(double a, double b) { System.out.println("This is a constructor with double parameters"); } } class Main { public static void main(String[] args) { Product obj1 = new Product(1,2); Product obj2 = new Product(1,2.0); Product obj3 = new Product(1.0,2.0); } }

Output

This is a constructor with integer parameters This is a constructor with double parameters This is a constructor with double parameters
Constructor Overriding In Java, constructors are not inherited by subclasses, hence, we cannot override constructors. If you try to write a superclass’s constructor in the subclass, the compiler treats it as a method and expects a return type, generating a compile-time error. However, we can call the constructor of the superclass from its subclasses using the super() keyword. These two concepts are fundamental to Java’s OOP and are used extensively in Java programming. They enhance the flexibility and reusability of code, and allow us to design more efficient and effective programs.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ Polymorphism ★ method overloading ★ method overriding ★Constructor

Tutorials